<?php

namespace app\common\ShaoHuoPay\Gateways\Wechat;

use Symfony\Component\HttpFoundation\JsonResponse;
use app\common\ShaoHuoPay\tools\Str;
use app\common\ShaoHuoPay\Gateways\Wechat\Gateway;
use app\common\ShaoHuoPay\Gateways\Wechat\WxTools;

class AppGateway extends Gateway
{
    /**
     * 支付订单
     * @param $endpoint
     * @param array $payload
     * @return static
     */
    public function pay($endpoint, array $payload)
    {
        $payload['appid'] = $this->config->get('appid');
        $payload['trade_type'] = $this->getTradeType();

        //预支付
        //$prepay = $this->preOrder('pay/unifiedorder', $payload);

        $payRequest = [
            'appid'     => $payload['appid'],
            'partnerid' => $payload['mch_id'],
            'prepayid'  => $this->preOrder('pay/unifiedorder', $payload)->prepay_id,
            'timestamp' => strval(time()),
            'noncestr'  => Str::random(),
            'package'   => 'Sign=WXPay',
        ];

        $payRequest['sign'] = WxTools::generateSign($payRequest, $this->config->get('key'));

        //Log::debug('Paying An App Order:', [$endpoint, $payRequest]);

        return JsonResponse::create($payRequest);
    }

    /**
     * 获取支付类型
     * @return string
     */
    protected function getTradeType()
    {
        return 'APP';
    }
}
